import Vue from 'vue'

const ToastConstructor = Vue.extend(require('./toast.vue'))

let instance = null

const getAnInstance = () => {
  if (instance) {
    return instance
  }

  return new ToastConstructor({
    el: document.createElement('div'),
  })
}

const removeDom = (el) => {
  if (el.parentNode) {
    el.parentNode.removeChild(el)
  }
}

ToastConstructor.prototype.remove = function remove() {
  this.show = false
  instance = null
  removeDom(this.$el)
}

const Toast = (options = {}) => {
  instance = getAnInstance()
  const duration = options.duration || 3000
  instance.message = typeof options === 'string' ? options : options.message
  instance.isShowMask = options.isShowMask
  clearTimeout(instance.timer)

  document.body.appendChild(instance.$el)

  Vue.nextTick(() => {
    instance.show = true

    if (duration) {
      instance.timer = setTimeout(() => {
        if (instance) {
          instance.remove()
        }
      }, duration)
    }
  })

  return instance
}

export default Toast
